﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Sockets;
using System.Text;
using Comunication;

namespace VehicleAgent
{
    class PacketProcessor:ITcpPacketProcessor
    {
#region Events
        public delegate void BoolResponseEvent(bool response);

        public delegate void Event();
        public event BoolResponseEvent TakeVehicleResponseReceived;
        public event Event LowBalanceReceived;
        public event Event OutOfCreditReceived;
        public event Event ConnectionEnded;
#endregion


        public void ProcessPacket(byte[] buffer, Socket handler)
        {
            UTF8Encoding decoder = new UTF8Encoding();
            string header = decoder.GetString(buffer, 0, 3);
            string cmd = decoder.GetString(buffer, 3, 2);
            int dataLength = int.Parse(decoder.GetString(buffer, 5, 5));
            string data;

            Commands command = (Commands)int.Parse(cmd);

            switch (command)
            {
                case Commands.TAKE_VEHICLE_RESPONSE:
                    data = decoder.GetString(buffer, 10, dataLength);
                    if (TakeVehicleResponseReceived != null)
                        TakeVehicleResponseReceived(bool.Parse(data));
                    break;
                case Commands.LOW_BALANCE:
                    if (LowBalanceReceived != null)
                        LowBalanceReceived();
                    break;
                case Commands.OUT_OF_CREDIT:
                    if (OutOfCreditReceived != null)
                        OutOfCreditReceived();
                    break;
                default:
                    break;
            }
        }

        public void EndConnection(Socket handler)
        {
            if (ConnectionEnded != null)
                ConnectionEnded();
        }

     
    }
}
